package create_thread;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/4/25
 * Time:19:58
 * 创建线程方法 3 -- 实现Callable接口+Future 的方式
 * 创建并得到线程执行的结果
 **/
public class Thread6 {
    static class MyCallable implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            //生成一个随机数
            int num = new Random().nextInt(10);
            System.out.println("子线程名称" + Thread.currentThread().getName() + ",随机数" + num);
            return num;
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.创建一个Callable
        MyCallable myCallable = new MyCallable();
        //2.创建一个FutureTask对象来接收返回值
        FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
        //3.创建Thread
        Thread thread = new Thread(futureTask);
        //启动线程
        thread.start();
        //得到线程执行结果
        int result = futureTask.get();
        System.out.println(String.format("线程名称:%s,数字:%d",
                Thread.currentThread().getName(), result));
    }
}
